package com.ht.api.task;

import cn.hutool.json.JSONObject;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.db.util.HtUtil;
import com.ht.api.service.AudienceService;
import com.ht.api.util.NoticeUtil;

import javax.sql.DataSource;

public class AudienceInitTask implements TaskHandler {

	@Override
	public String getName() {
		return "初始化人群";
	}

    @Override
    public boolean handler(JSONObject requestParam, String groupId, long taskId) {

        long tenantId = requestParam.getLong("tenant_id");

        DataSource ds = DbConfig.tenantDSMap.get(tenantId);
        StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);

        String audienceId = requestParam.getStr("audience_id");
        String userId = requestParam.getStr("user_id");

        Entity audience = Db.createSqlParser("audience").where("main_id", audienceId).findOne(ds);

        AudienceService.refreshAudience(ds, config, audience);

        NoticeUtil.send( "人群["+audience.getStr("name")+"]已初始化成功！", 1, userId);

        audience.set("init_status", 2);
        Db.insert(ds, audience);

        HtUtil.createLog(ds, audienceId, "初始化完成！");

        return true;
    }
}
